package com.chenju.invokechainservice.component;

import com.chenju.invokechainservice.utils.CmdExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeoutException;

@Component
public class CodeExecutor {
    private final static Logger logger = LoggerFactory.getLogger(CodeExecutor.class);

    private final GitComponent git;

    private final BuildComponent build;

    public CodeExecutor(GitComponent git, BuildComponent build) {
        this.git = git;
        this.build = build;
    }

    public void cloneCode(String giturl, String codePath, String version){
        try {
            git.cloneRepository(giturl, codePath, version);
            logger.info("分支【"+version+"】代码从【"+giturl+"】克隆至目录【"+codePath+"】成功!");
        } catch (Exception e) {
            logger.info("分支【"+version+"】代码从【"+giturl+"】克隆至目录【"+codePath+"】失败!");
        }
    }

    public void compileCode(String codePath, String env){
        String[] compileCmd = null;
        String buildTool = build.getBuildTool();
        if ("gradle".equals(buildTool)){
            compileCmd = new String[]{"cd " + codePath + "&&gradle clean build -x test"};
        } else {
            compileCmd = new String[]{"cd " + codePath + "&&mvn clean compile -Dmaven.test.skip=true" + (env == null || env.equals("") ? "" : "-P=" + env)};
        }
        try {
            int exitCode = CmdExecutor.executeCmd(compileCmd, 600000L);
            if (exitCode != 0){
                logger.info("目录【"+codePath+"】中代码打包失败!");
            }
            logger.info("目录【"+codePath+"】中代码打包成功!");
        } catch (TimeoutException e){
            logger.info("目录【"+codePath+"】中代码打包耗时超过10分钟!");
        } catch (Exception e) {
            logger.info("目录【"+codePath+"】中代码打包遇到未知异常!");
        }
    }


}
